<?php
/**
 *
 *   User:King
 *   Date:2021/11/3 17:10
 */

namespace app\api\library;

use GuzzleHttp\Exception\RequestException;
use WechatPay\GuzzleMiddleware\WechatPayMiddleware;
use WechatPay\GuzzleMiddleware\Util\PemUtil;
use GuzzleHttp;
use think\Log;
class WechatPay
{


    public $client;
    public $merchantId = '';
    public $app_id     = '';

    public function __construct(){

        $wechat_config =  config('wechat');
        $this->merchantId = $wechat_config['merchantId'];
        $this->app_id = $wechat_config['app_id'];

        // 商户相关配置，
        $merchantPrivateKey = PemUtil::loadPrivateKey($wechat_config['merchantPrivateKey']); // 商户私钥
        // 微信支付平台配置
        $wechatpayCertificate = PemUtil::loadCertificate($wechat_config['wechatpayCertificate']); // 微信支付平台证书文件路径

        // 构造一个WechatPayMiddleware
        $wechatpayMiddleware = WechatPayMiddleware::builder()
            ->withMerchant($this->merchantId, $wechat_config['merchantSerialNumber'], $merchantPrivateKey) // 传入商户相关配置
            ->withWechatPay([ $wechatpayCertificate ]) // 可传入多个微信支付平台证书，参数类型为array
            ->build();

        // 将WechatPayMiddleware添加到Guzzle的HandlerStack中
        $stack = GuzzleHttp\HandlerStack::create();
        $stack->push($wechatpayMiddleware, 'wechatpay');

        // 创建Guzzle HTTP Client时，将HandlerStack传入，接下来，正常使用Guzzle发起API请求，WechatPayMiddleware会自动地处理签名和验签
        $this->client = new GuzzleHttp\Client(['handler' => $stack]);

    }
    //创建
    public function createCoupon($data)
    {
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/coupon-stocks', //请求URL
                [
                    // JSON请求体
                    'json' => $data,
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }

    //激活
    public function startCoupon($stock_id)
    {
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/'.$stock_id.'/start', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        "stock_creator_mchid" => $this->merchantId,
                    ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }

    //发放
    public function sendCoupon($stock_id,$order_no,$openid)
    {

        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/users/'.$openid.'/coupons', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        "stock_id" => $stock_id,
                        "out_request_no" => $order_no,
                        "appid" => $this->app_id,
                        "stock_creator_mchid" => $this->merchantId,
                    ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }

    //暂停
    public function pauseCoupon($stock_id)
    {
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/'.$stock_id.'/pause', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        "stock_creator_mchid" => $this->merchantId,
                    ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }
    //重启
    public function restartCoupon($stock_id)
    {
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/'.$stock_id.'/restart', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        "stock_creator_mchid" => $this->merchantId,
                    ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }

    //设置异步通知地址
    public function setCallback($url)
    {
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/callbacks', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        "mchid" => $this->merchantId,
                        "notify_url" => $url,
                    ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }



    //查询详情
    public function searchInfo($stock_id)
    {

        try {
            $resp = $this->client->request(
                'GET',
                'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/'.$stock_id.'?stock_creator_mchid='.$this->merchantId, //请求URL
                [
                    'headers' => [ 'Accept' => 'application/json']
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }


    protected function handleSuccess($resp)
    {
        $statusCode = $resp->getStatusCode();
        if ($statusCode == 200) { //处理成功
            return [1,json_decode($resp->getBody()->getContents(),true)];
        } else if ($statusCode == 204) { //处理成功，无返回Body
            return [2,null];
        }
    }

    protected function handleFail($e)
    {

        if ($e->hasResponse()) {
            return [0,json_decode($e->getResponse()->getBody(),true)];
        }
        return [0,$e->getMessage()];

    }


    public function transfer($data)
    {
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        'appid'=>$this->app_id,
                        'out_bill_no' => $data['out_bill_no'],//必填 string(32)【商户单号】
                        'transfer_scene_id' => '1000',//必填 string(36) 1000（现金营销），1006（企业报销）等
                        'openid' => $data['openid'],//必填 string(64)
                        'transfer_amount' => $data['transfer_amount'],//必填 integer【转账金额】 转账金额单位为“分”
                        'transfer_remark' => $data['transfer_remark']??'新会员有礼',//必填 string(32)【转账备注】
                        'notify_url' => cdnurl('/api/notify/mchtransfer',true),//'https://test.xinyaoan.com/api/notify/mchtransfer',//选填 string(256)【通知地址】
                        'user_recv_perception'=>$data['user_recv_perception']??'现金奖励',
                        //必填 array[object]
                        'transfer_scene_report_infos' => $data['transfer_scene_report_infos'],
//                            [
//                                [
//                                    'info_type' => '活动名称',//必填 string(15)【信息类型】
//                                    'info_content' => '新人有礼',//必填 string(32)【信息内容】
//                                ],
//                                [
//                                    'info_type' => '奖励说明',//必填 string(15)【信息类型】
//                                    'info_content' => '新人抽奖一等奖',//必填 string(32)【信息内容】
//                                ]
//                            ]
                        ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            return $this->handleSuccess($resp);
        } catch (RequestException $e) {
            return $this->handleFail($e);
        }
    }


}